<template>
    <el-aside style="padding: 0px; width: 250px; height: 100%">
        <DatasetPanel ref="dataset_panel" @load-data="onLoadData"></DatasetPanel>
    </el-aside>
    <el-main style="padding: 0px; height: 100%">
        <ImageRegion ref="image_region" :_region_id="`editor`" :_readonly="false" :_toolbar="_algo_type"
            :_sync_ops="false" :_show_name="false" :_highlight="false" @update-image-info="onUpdateImageInfo"
            @delete-label="onDeleteLabel" @select-label="onSelectLabel" @unselect-label="onUnselectLabel"
            @pre-label-data="preLabelData" @next-label-data="nextLabelData" @delete-label-data="deleteLabelData"
            @autolabel="onAutolabel">
        </ImageRegion>
    </el-main>
    <el-aside style="padding: 0px; width: 250px; height: 100%">
        <component :is="labelsComponent" v-if="labelsComponent" ref="label_result"
            @change-label-mode="onChangeLabelMode" @delete-label="onDeleteLabel" @select-label="onSelectLabel" />
    </el-aside>
</template>

<script setup>
import API from '@/js/api';
import LabelConfig from '@/js/models/LabelConfig';
import { ref, onMounted, onUnmounted, getCurrentInstance, provide, inject, computed, defineAsyncComponent } from 'vue';
import DatasetPanel from '@/components/ToolPages/DatasetPanel.vue';
import ImageRegion from '@/components/ToolPages/ImageRegion.vue';

provide('vueToolPanel', { setConfig });
const emit = defineEmits(['loadDataset', 'selectPanel']);
defineExpose({ loadDataset, handleKeyDown });

// 基础变量(快捷键调用)
const name = 'ToolPanel';
let vueApp = inject('vueApp');
const { proxy } = getCurrentInstance();
const methods = {
    preLabelData: preLabelData,
    nextLabelData: nextLabelData,
    deleteLabelData: deleteLabelData,
    deleteSelection: deleteSelection
};

// 成员变量
let _dataset_id = ref('');
let _label_result = null;
let _algo_type = ref(null);

// 动态加载标注结果看板
const labelsComponent = computed(() => {
    if (!_algo_type.value) return null;

    return defineAsyncComponent(async () => {
        let compPath = `./${_algo_type.value.supertype}/${_algo_type.value.type}/LabelResult.vue`;
        try {
            console.log(`加载组件 ${compPath}`);
            const module = await import(`./${_algo_type.value.supertype}/${_algo_type.value.type}/LabelResult.vue`);
            return module.default;
        } catch (error) {
            console.error(`组件 ${compPath} 加载失败`, error);
            return null;
        }
    });
});

async function loadDataset(dataset_id) {
    // console.log('loadDataset dataset_id = ', dataset_id);
    if (!dataset_id) {
        console.warn('dataset_id is null!');
        return;
    }

    _dataset_id.value = dataset_id;
    const loading = ElLoading.service({
        lock: true,
        text: '数据集加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    // 获取dataset的基础信息
    let result = await API.invoke('GetDatasetInfo', { dataset_id: dataset_id });
    if (result.code === 0) {
        let dataset_info = result.msg;
        await proxy.$refs.dataset_panel.loadDataset(dataset_info);
        proxy.$refs.image_region.loadDataset(dataset_info);
        loading.close();
    } else {
        console.error('GetDatasetInfo Failed!');
        loading.close();
    }
}

function onLoadData(data) {
    // console.log(`ToolPanel::loadData data = `, data);
    _label_result = data.label_result;
    proxy.$refs.image_region && proxy.$refs.image_region.loadData(data);
    proxy.$refs.label_result && proxy.$refs.label_result.loadData(data, proxy.$refs.label_result);
}

function onUpdateImageInfo(info) {
    // console.log(`ToolPanel updateImageInfo info = `, info);
    proxy.$refs.label_result && proxy.$refs.label_result.updateImageInfo(`${info.width} x ${info.height}`);
}

function onDeleteLabel(label_id) {
    // console.log(`ToolPanel onDeleteLabel label_id = `, label_id);
    _label_result && _label_result.deleteLabel(label_id);
}

function onSelectLabel(label_id) {
    // console.log('ToolPanel onSelectLabel label_id = ', label_id);
    _label_result && _label_result.selectLabel(label_id);
}

function onUnselectLabel() {
    _label_result && _label_result.unselectLabel();
}

function deleteSelection() {
    _label_result && _label_result.deleteSelection();
}

function handleKeyDown(event) {
    LabelConfig.runShortCuts('ToolPanel', methods, event);
    proxy.$refs.image_region && proxy.$refs.image_region.handleKeyDown(event);
}

function preLabelData() {
    proxy.$refs.dataset_panel && proxy.$refs.dataset_panel.preLabelData();
}

function nextLabelData() {
    proxy.$refs.dataset_panel && proxy.$refs.dataset_panel.nextLabelData();
}

function deleteLabelData() {
    proxy.$refs.dataset_panel && proxy.$refs.dataset_panel.deleteLabelData();
}

function onAutolabel() {
    proxy.$refs.image_region && proxy.$refs.image_region.autolabel();
}

function setConfig(config) {
    _label_result && _label_result.setConfig(config);
}

function onChangeLabelMode(mode) {
    proxy.$refs.image_region && proxy.$refs.image_region.changeLabelMode(mode);
}

onMounted(() => {
    _algo_type.value = vueApp.getAlgoType();
});

onUnmounted(() => { });
</script>

<style scoped>
.el-aside {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
